package com.example.demo.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.demo.utils.Jwt;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JTWinterceptors implements HandlerInterceptor {

    @Override
   public  boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
   {
       if(request.getMethod().equals("OPTIONS")){
           response.setHeader("Access-Control-Allow-Origin", "*");
           response.setHeader("Access-Control-Allow-Headers","*");
           response.setHeader("Access-Control-Allow-Methods","*");
           response.setHeader("Access-Control-Allow-Credentials","true");
           response.setHeader("Access-Control-Max-Age","3600");
           return true;
       }
       Map<String,Object> map=new HashMap<>();
       String token = request.getHeader("token");
       try {
           Jwt.verify(token);
           return true;
       }catch (SignatureVerificationException e)
       {
           e.printStackTrace();
           map.put("msg","无效签名");
       }catch (TokenExpiredException e)
       {
           e.printStackTrace();
           map.put("msg","无效签名");
       }catch (AlgorithmMismatchException e)
       {
           e.printStackTrace();
           map.put("msg","token 算法不一致！");
       }catch (Exception e)
       {
           e.printStackTrace();
           map.put("msg","token无效");
       }
       map.put("state",false);
       //将map 转为json
       String json = new ObjectMapper().writeValueAsString(map);
       response.setContentType("application/json;charset=UTF-8");
       response.getWriter().println(json);
       return false;




   }

}